<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Location, Calendar, View, Star, Edit } from '@element-plus/icons-vue'
import {
  getTravelNoteDetail,
  likeTravelNote,
  unlikeTravelNote,
  favoriteTravelNote,
  unfavoriteTravelNote,
  getTravelNoteComments,
  addTravelNoteComment,
  increaseTravelNoteView
} from '../../api/travelNote'
import { authUtils } from '../../utils/auth'

const route = useRoute()
const router = useRouter()
const noteId = parseInt(route.params.id)

// 社区入口只读模式：?readonly=1 / true
const browseOnly = computed(() => {
  const q = route.query?.readonly
  return q === '1' || q === 'true'
})

// 游记详情
const note = ref(null)
const loading = ref(true)

// 评论相关
const commentContent = ref('')
const comments = ref([])
const commentsLoading = ref(false)

// 判断是否是作者
const isAuthor = computed(() => {
  if (!note.value || !authUtils.isLoggedIn()) return false
  const currentUser = authUtils.getCurrentUser()
  // 后端返回的是 user_id 字段
  return currentUser && note.value.user_id === currentUser.id
})

// 加载游记详情
const loadNoteDetail = async () => {
  loading.value = true
  try {
    const result = await getTravelNoteDetail(noteId)

    if (result.success) {
      note.value = result.data
    } else {
      ElMessage.error(result.message || '加载失败')
    }
  } catch (error) {
    console.error('加载游记详情失败:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 加载评论列表
const loadComments = async () => {
  commentsLoading.value = true
  try {
    const result = await getTravelNoteComments(noteId, {
      page: 1,
      pageSize: 20
    })

    if (result.success) {
      comments.value = result.data.list
    }
  } catch (error) {
    console.error('加载评论失败:', error)
  } finally {
    commentsLoading.value = false
  }
}

// 处理标签数据
const parseTags = (tags) => {
  if (!tags) return []

  // 如果已经是数组，直接返回
  if (Array.isArray(tags)) {
    return tags
  }

  // 如果是字符串，尝试解析
  if (typeof tags === 'string') {
    try {
      // 尝试解析 JSON 字符串
      const parsed = JSON.parse(tags)
      if (Array.isArray(parsed)) {
        return parsed
      }
    } catch (e) {
      // 如果不是 JSON，按逗号分割
      return tags
        .split(',')
        .map((t) => t.trim())
        .filter((t) => t)
    }
  }

  return []
}

// 显示数据（带默认值）
const displayNote = computed(() => {
  if (!note.value) return null

  return {
    id: note.value.id,
    title: note.value.title || '无标题',
    cover: note.value.cover_image || 'https://picsum.photos/1200/600?random=99',
    author:
      note.value.author?.nickname || note.value.author?.username || '匿名',
    authorAvatar:
      note.value.author?.avatar || 'https://picsum.photos/100/100?random=120',
    cityName: note.value.city || '未知',
    date: note.value.start_date || note.value.created_at,
    views: note.value.view_count || 0,
    likes: note.value.like_count || 0,
    favorites: note.value.favorite_count || 0,
    comments: note.value.comment_count || 0,
    description: note.value.description || '',
    tags: parseTags(note.value.tags),
    content: note.value.content || '<p>暂无内容</p>',
    visibility: note.value.visibility,
    status: note.value.status,
    is_liked: note.value.is_liked || false,
    is_favorited: note.value.is_favorited || false
  }
})

// 状态文本
const statusText = computed(() => {
  if (!displayNote.value) return '未知'
  const v = displayNote.value.visibility
  const s = displayNote.value.status
  if (v === 'public' && s === 'approved') return '公开'
  if (v === 'public' && s === 'pending') return '审核中'
  if (v === 'private') return '私密'
  if (s === 'draft') return '草稿'
  return '未知'
})

// 状态类型
const statusType = computed(() => {
  if (!displayNote.value) return 'info'
  const v = displayNote.value.visibility
  const s = displayNote.value.status
  if (v === 'public' && s === 'approved') return 'success'
  if (v === 'public' && s === 'pending') return 'warning'
  if (v === 'private' || s === 'draft') return 'info'
  return 'info'
})

// 点赞/取消点赞
const toggleLike = async () => {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    if (displayNote.value.is_liked) {
      const result = await unlikeTravelNote(noteId)
      if (result.success) {
        note.value.is_liked = false
        note.value.like_count--
        ElMessage.success('已取消点赞')
      }
    } else {
      const result = await likeTravelNote(noteId)
      if (result.success) {
        note.value.is_liked = true
        note.value.like_count++
        ElMessage.success('点赞成功')
      }
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 收藏/取消收藏
const toggleFavorite = async () => {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    if (displayNote.value.is_favorited) {
      const result = await unfavoriteTravelNote(noteId)
      if (result.success) {
        note.value.is_favorited = false
        note.value.favorite_count--
        ElMessage.success('已取消收藏')
      }
    } else {
      const result = await favoriteTravelNote(noteId)
      if (result.success) {
        note.value.is_favorited = true
        note.value.favorite_count++
        ElMessage.success('收藏成功')
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    const result = await addTravelNoteComment(noteId, {
      content: commentContent.value.trim()
    })

    if (result.success) {
      ElMessage.success('评论成功')
      commentContent.value = ''
      // 重新加载评论列表
      loadComments()
      // 更新评论数
      if (note.value) {
        note.value.comment_count++
      }
    } else {
      ElMessage.error(result.message || '评论失败')
    }
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败')
  }
}

// 编辑游记
const goToEdit = () => {
  if (browseOnly.value) {
    ElMessage.warning('当前为仅浏览模式，不能编辑游记')
    return
  }
  router.push(`/travel-note/${noteId}/edit`)
}

// 增加浏览量（埋点）
const trackView = async () => {
  try {
    await increaseTravelNoteView(noteId)
    console.log('浏览量已记录')
  } catch (error) {
    // 静默失败，不影响用户体验
    console.error('浏览量记录失败:', error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadNoteDetail()
  loadComments()
  // 调用埋点，增加浏览量
  trackView()
})
</script>

<template>
  <div class="travel-note-detail-container" v-loading="loading">
    <template v-if="displayNote">
      <div class="edit-button-float" v-if="isAuthor && !browseOnly">
        <el-button type="primary" @click="goToEdit" size="large" round>
          <el-icon><Edit /></el-icon>
          编辑游记
        </el-button>
      </div>

      <!-- 笔记头部信息 -->
      <div
        class="note-header"
        :style="{ backgroundImage: `url(${displayNote.cover})` }"
      >
        <div class="note-header-overlay">
          <div class="note-header-content">
            <h1>{{ displayNote.title }}</h1>
            <div class="note-meta">
              <div class="note-author">
                <el-avatar
                  :size="40"
                  :src="displayNote.authorAvatar"
                ></el-avatar>
                <span>{{ displayNote.author }}</span>
              </div>
              <div class="note-info">
                <span
                  ><el-icon><Location /></el-icon>
                  {{ displayNote.cityName }}</span
                >
                <span
                  ><el-icon><Calendar /></el-icon> {{ displayNote.date }}</span
                >
                <span
                  ><el-icon><View /></el-icon>
                  {{ displayNote.views }} 阅读</span
                >
                <el-tag :type="statusType" size="small">{{
                  statusText
                }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 笔记内容 -->
      <div class="note-content">
        <div class="note-description">
          {{ displayNote.description }}
        </div>

        <div class="note-content-html" v-html="displayNote.content"></div>

        <!-- 标签 -->
        <div
          class="note-tags"
          v-if="displayNote.tags && displayNote.tags.length > 0"
        >
          <span class="tags-label">标签：</span>
          <el-tag
            v-for="(tag, index) in displayNote.tags"
            :key="index"
            type="info"
            effect="plain"
            size="default"
          >
            {{ tag }}
          </el-tag>
        </div>

        <!-- 点赞收藏操作 -->
        <div class="note-actions">
          <el-button
            :type="displayNote.is_liked ? 'primary' : ''"
            @click="toggleLike"
          >
            <el-icon><Star /></el-icon>
            {{ displayNote.is_liked ? '已点赞' : '点赞' }} ({{
              displayNote.likes
            }})
          </el-button>
          <el-button
            :type="displayNote.is_favorited ? 'success' : ''"
            @click="toggleFavorite"
          >
            <el-icon><Star /></el-icon>
            {{ displayNote.is_favorited ? '已收藏' : '收藏' }} ({{
              displayNote.favorites
            }})
          </el-button>
        </div>

        <!-- 评论区 -->
        <div class="note-comments">
          <h3>评论 ({{ displayNote.comments }})</h3>

          <div class="comment-form">
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
            />
            <el-button type="primary" @click="submitComment"
              >发表评论</el-button
            >
          </div>

          <div class="comment-list" v-loading="commentsLoading">
            <el-empty
              v-if="!commentsLoading && !comments.length"
              description="暂无评论"
            />
            <div
              v-else
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-user">
                <el-avatar
                  :size="32"
                  :src="
                    comment.user?.avatar ||
                    'https://picsum.photos/32/32?random=99'
                  "
                ></el-avatar>
                <div class="comment-info">
                  <div class="comment-username">
                    {{
                      comment.user?.nickname || comment.user?.username || '匿名'
                    }}
                  </div>
                  <div class="comment-time">{{ comment.created_at }}</div>
                </div>
              </div>
              <div class="comment-content">
                {{ comment.content }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <el-empty v-else-if="!loading" description="游记不存在或已被删除" />
  </div>
</template>

<style scoped>
.travel-note-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
}

/* 浮动编辑按钮 */
.edit-button-float {
  position: fixed;
  top: 100px;
  right: 40px;
  z-index: 1000;
  animation: fadeInRight 0.5s ease-out;
}

@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.edit-button-float .el-button {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.edit-button-float .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.note-header {
  height: 300px;
  background-size: cover;
  background-position: center;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 30px;
}

.note-header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.3),
    rgba(0, 0, 0, 0.7)
  );
  display: flex;
  align-items: flex-end;
}

.note-header-content {
  padding: 20px;
  color: white;
  width: 100%;
}

.note-header-content h1 {
  font-size: 32px;
  margin: 0 0 15px;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.note-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.note-info {
  display: flex;
  gap: 15px;
}

.note-info span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.note-content {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.note-description {
  font-size: 16px;
  line-height: 1.6;
  color: #606266;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.note-sections {
  margin-bottom: 30px;
}

.note-section {
  margin-bottom: 30px;
}

.note-section h2 {
  font-size: 22px;
  margin: 0 0 15px;
  color: #303133;
}

.section-image {
  margin-bottom: 15px;
}

.section-image img {
  width: 100%;
  border-radius: 8px;
}

.note-section p {
  font-size: 16px;
  line-height: 1.6;
  color: #606266;
  margin: 0;
}

.note-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin: 30px 0 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.tags-label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-right: 5px;
}

.note-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.note-comments h3 {
  font-size: 18px;
  margin-bottom: 20px;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-form .el-button {
  margin-top: 10px;
  float: right;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-info {
  display: flex;
  flex-direction: column;
}

.comment-username {
  font-weight: bold;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  color: #606266;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .note-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .note-info {
    flex-direction: column;
    gap: 5px;
  }

  .note-actions {
    gap: 10px;
  }

  .author-actions,
  .interaction-actions {
    flex-direction: column;
    gap: 10px;
  }

  .author-actions .el-button,
  .interaction-actions .el-button {
    width: 100%;
  }
}
</style>
